﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Configuration;

using TnPlus.Entities.Models;
using TnPlus.Biz;
using VPBS.DB2.DAL;
using VPBS.Informix.DAL;
using VPBS.SqlClient.DAL;
using VPBS.Oracle.DAL;


namespace TransferDataWinSevice
{
    public partial class TrnsDataWinService : ServiceBase
    {
        System.Timers.Timer timer;
        EventLog eventLog;
        decimal threshold = 0;
        public TrnsDataWinService()
        {
            InitializeComponent();

            // Reads settings from app.config
            this.ServiceName = ConfigurationSettings.AppSettings["serviceName"];
            string eventLogName = ConfigurationSettings.AppSettings["eventLogName"];
            string eventLogSource = ConfigurationSettings.AppSettings["eventLogSource"];
            threshold = decimal.Parse(ConfigurationSettings.AppSettings["threshold"]);

            // Initializes eventlog
            if (!EventLog.SourceExists(eventLogSource))
                EventLog.CreateEventSource(eventLogSource, eventLogName);

            eventLog = new EventLog();
            ((System.ComponentModel.ISupportInitialize)(eventLog)).BeginInit();

            eventLog.Source = eventLogSource;

            // Registers the application
            eventLog.Log = eventLogName;

            ((System.ComponentModel.ISupportInitialize)(eventLog)).EndInit();

            //CollectAndTransferData();
        }

        protected override void OnStart(string[] args)
        {
            eventLog.WriteEntry("+++++++++++++ START SMS SERVICE +++++++++++++", EventLogEntryType.Warning);

            // Runs the process every X minutes
            int interval = Int32.Parse(ConfigurationSettings.AppSettings["interval"]) * 1000;
            timer = new System.Timers.Timer();
            timer.Interval = interval;
            timer.Elapsed += new System.Timers.ElapsedEventHandler(CollectAndTransferData);
            timer.Start();
        }

        protected void CollectAndTransferData(object obj, System.Timers.ElapsedEventArgs e)
        {
            int startHour = Int32.Parse(ConfigurationSettings.AppSettings["startTime"]);
            int stopHour = Int32.Parse(ConfigurationSettings.AppSettings["stopTime"]);
            DateTime now = DateTime.Now;
            string strMinute = now.Minute.ToString();
            if (now.Minute < 10) strMinute = "0" + now.Minute.ToString();
            int Time = int.Parse(now.Hour.ToString() + strMinute);

            if ((Time >= 0 && Time < startHour) || (Time >= stopHour && Time <= 2300) ||
                ThdHolydayDateDAL.CheckOfHolydayDate() == true)
                return;

            DataSet DsPrtlDebtAcct = TnDebtDAL.Get_DebterLst();// Danh sách tài khoản dư nợ Tn
            if (DsPrtlDebtAcct != null && DsPrtlDebtAcct.Tables[0].Rows.Count > 0)
            {
                DataTable DataTableInfo = new DataTable();
                WebService.Service ObjWS = new WebService.Service();

                PortfolioTodayInfo portfolioTodayInfo = new PortfolioTodayInfo();
                PortfolioTodayService portfolioTodayService = new PortfolioTodayService();

                CashTodayInfo cashTodayInfo = new CashTodayInfo();
                CashTodayService cashTodayService = new CashTodayService();

                DebtTodayInfo debtTodayInfo = new DebtTodayInfo();
                DebtTodayService debtTodayService = new DebtTodayService();

                CallSMSInfo callSMSInfo = new CallSMSInfo();
                CallSMSService callSMSService = new CallSMSService();

                string IdCommon = DateTime.Now.ToString("yyyyMMdd") + "-" + Guid.NewGuid().ToString();
                //Id chung cho một lượt transfer
                string custcode = "";
                string custacct = "1";
                string AccountNo = "";
                decimal IMCustomer, AdjustRate;

                bool Flag = true;

                for (int i = 0; i < DsPrtlDebtAcct.Tables[0].Rows.Count; i++)
                {
                    Flag = true;
                    custcode = DsPrtlDebtAcct.Tables[0].Rows[i][0].ToString().Substring(4);
                    AccountNo = custcode + custacct;
                    IMCustomer = TnIMCustomerDAL.Get_IMCustomer();
                    AdjustRate = TnAdjustRateDAL.Get_AdjustRate(custcode, custacct);
                    DataTableInfo = PortfolioDAL.Get_PortfolioToday(AccountNo);
                    if (DataTableInfo != null && DataTableInfo.Rows.Count > 0)
                    {
                        for (int j = 0; j < DataTableInfo.Rows.Count; j++)
                        {
                            portfolioTodayInfo.IdPortfolio = Guid.NewGuid();
                            portfolioTodayInfo.PostDate = DateTime.Now;
                            portfolioTodayInfo.IdCommon = IdCommon;
                            portfolioTodayInfo.AccountNo = AccountNo;
                            portfolioTodayInfo.SecSymbol = DataTableInfo.Rows[j]["SecSymbol"].ToString().Trim();
                            portfolioTodayInfo.SecType = DataTableInfo.Rows[j]["SecType"].ToString();
                            portfolioTodayInfo.Unit = int.Parse(DataTableInfo.Rows[j]["Unit"].ToString());
                            portfolioTodayInfo.PriceMkt = StockPriceDAL.MarketPrice(portfolioTodayInfo.SecSymbol,
                                                                                    startHour, stopHour);
                            portfolioTodayInfo.IMStock =
                                TcmstMarginSecuritiesDAL.Get_MarginSecurities(portfolioTodayInfo.SecSymbol,
                                                                              DateTime.Now.ToString("yyyy/MM/dd"));
                            portfolioTodayInfo.IMCustomer = IMCustomer;
                            portfolioTodayInfo.AdjustRate = AdjustRate;
                            if (portfolioTodayInfo.PriceMkt <= 0)
                                Flag = false;
                            portfolioTodayService.Insert(portfolioTodayInfo);
                        }
                    }
                    //CashToday
                    cashTodayInfo.IdCash = Guid.NewGuid();
                    cashTodayInfo.PostDate = DateTime.Now;
                    cashTodayInfo.IdCommon = IdCommon;
                    cashTodayInfo.AccountNo = AccountNo;
                    cashTodayInfo.Cash = 1000M*
                                         decimal.Parse(
                                             CashDAL.Get_CashToday(AccountNo).Rows[0]["CashBalance"].ToString());
                    cashTodayInfo.SecType = "Cash";
                    cashTodayService.Insert(cashTodayInfo); //Insert Cash

                    cashTodayInfo.IdCash = Guid.NewGuid();
                    cashTodayInfo.PostDate = DateTime.Now;
                    cashTodayInfo.Cash = ObjWS.GetTien_CotheUng_SauTinhPhi(custcode, custacct);
                    cashTodayInfo.SecType = "CanAdvance";
                    if (cashTodayInfo.Cash > 0)
                        cashTodayService.Insert(cashTodayInfo); //Insert CanAdvance

                    cashTodayInfo.IdCash = Guid.NewGuid();
                    cashTodayInfo.PostDate = DateTime.Now;
                    cashTodayInfo.Cash = 1000M*
                                         decimal.Parse(CashDAL.Get_CashToday(AccountNo).Rows[0]["Collateral"].ToString());
                    cashTodayInfo.SecType = "Collateral";
                    if (cashTodayInfo.Cash > 0)
                        cashTodayService.Insert(cashTodayInfo); //Insert Collateral

                    //DebtToday
                    debtTodayInfo.IdDebt = Guid.NewGuid();
                    debtTodayInfo.PostDate = DateTime.Now;
                    debtTodayInfo.IdCommon = IdCommon;
                    debtTodayInfo.AccountNo = AccountNo;
                    debtTodayInfo.Debt = TnDebtDAL.Get_Debt("026C" + custcode);
                    debtTodayService.Insert(debtTodayInfo);

                    //VCustomerInfo
                    decimal Ratio = decimal.Parse(
                        TnPlusVCustomerInfoDAL.Get_VCustomerInfo(AccountNo, IdCommon).Rows[0]["Ratio"].ToString());
                    decimal CallLMV = TnCustomerVipDAL.Get_CallLMV("026C" + custcode);
                    decimal ForceLMV = TnCustomerVipDAL.Get_ForceLMV("026C" + custcode);
                    if (Ratio < CallLMV)
                    {
                        callSMSInfo.IdCallSMS = Guid.NewGuid();
                        callSMSInfo.PostDate = DateTime.Now;
                        callSMSInfo.IdCommon = IdCommon;
                        callSMSInfo.AccountNo = AccountNo;
                        callSMSInfo.Asset =
                            decimal.Parse(
                                TnPlusVCustomerInfoDAL.Get_VCustomerInfo(AccountNo, IdCommon).Rows[0]["Asset"].ToString());
                        callSMSInfo.Debt =
                            decimal.Parse(
                                TnPlusVCustomerInfoDAL.Get_VCustomerInfo(AccountNo, IdCommon).Rows[0]["Debt"].ToString());
                        callSMSInfo.Ratio = Ratio;
                        callSMSInfo.CallLMV = TnCustomerVipDAL.Get_CallLMV("026C" + custcode);
                        callSMSInfo.ForceLMV = TnCustomerVipDAL.Get_ForceLMV("026C" + custcode);

                        callSMSInfo.AddCash = CallLMV * (callSMSInfo.Asset - decimal.Parse(TnPlusVCustomerInfoDAL.Get_VCustomerInfo(AccountNo, IdCommon).Rows[0]["CanAdvance"].ToString())) - decimal.Parse(TnPlusVCustomerInfoDAL.Get_VCustomerInfo(AccountNo, IdCommon).Rows[0]["Equity"].ToString());
                        if (Ratio <= CallLMV && Ratio > ForceLMV &&
                            Math.Abs(Ratio - TnPlusCallSmsDAL.Get_RatioOld(AccountNo))*100 >= threshold)
                        {
                            callSMSInfo.Action = "Call";
                            callSMSInfo.ContentSMS = ConfigurationSettings.AppSettings["SMSCallContent"].Replace(
                                "{AccountNo}", AccountNo)
                                .Replace("{Debt}",
                                         Math.Round(decimal.Parse((callSMSInfo.Debt/1000M).ToString()), 0).ToString())
                                .Replace("{Asset}",
                                         Math.Round(decimal.Parse((callSMSInfo.Asset/1000M).ToString()), 0).ToString())
                                .Replace("{Percent}", Math.Round(100M - Ratio*100M, 0).ToString())
                                .Replace("{AddValue}",
                                         Math.Round(decimal.Parse((callSMSInfo.AddCash/1000M).ToString()), 0).ToString());
                            callSMSInfo.ReceiveNo = TctCustomerInformationDAL.Get_PhoneNumber(custcode);
                            callSMSInfo.Status = null;
                            if (Flag == true)
                                callSMSService.Insert(callSMSInfo);
                        }
                        else if (Ratio < ForceLMV &&
                                 Math.Abs(Ratio - TnPlusCallSmsDAL.Get_RatioOld(AccountNo)) * 100 >= threshold)
                        {
                            callSMSInfo.Action = "Force";
                            callSMSInfo.ContentSMS = ConfigurationSettings.AppSettings["SMSForceContent"].Replace(
                                "{AccountNo}", AccountNo)
                                .Replace("{Debt}",
                                         Math.Round(decimal.Parse((callSMSInfo.Debt/1000M).ToString()), 0).ToString())
                                .Replace("{Asset}",
                                         Math.Round(decimal.Parse((callSMSInfo.Asset/1000M).ToString()), 0).ToString
                                             ())
                                .Replace("{Percent}", Math.Round(100M - Ratio*100M, 0).ToString());
                            callSMSInfo.ReceiveNo = TctCustomerInformationDAL.Get_PhoneNumber(custcode);
                            callSMSInfo.Status = null;
                            if (Flag == true)
                                callSMSService.Insert(callSMSInfo);
                        }
                    }
                }
            }
        }

        protected override void OnStop()
        {
            eventLog.WriteEntry("+++++++++++++ STOP SMS SERVICE +++++++++++++", EventLogEntryType.Warning);
        }
    }
}
